﻿using SaveSation.Entity;
using SaveSation.Common;
using Common.UI;
using DefPack.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SaveSation
{
    public partial class ItemForm : Form
    {
        public ItemForm()
        {
            InitializeComponent();
        }
        internal static DialogResult Show(ref ArchiveEntity? archive, List<GroupEntity> groups, bool create = false)
        {
            using (ItemForm item = new ItemForm())
            {
                item.Text = create ? "新增配置" : "编辑配置";
                if (create || archive == null)
                {
                    archive = new ArchiveEntity();
                }
                else
                {
                    item.textBox1.Text = archive.Name;
                    item.textBox2.Text = archive.Application;
                    item.textBox3.Text = archive.ArchivePath;
                    item.textBox4.Text = archive.SteamID;
                    item.textBox5.Text = archive.SortNumber.ToString();
                    string iconFile = Path.Combine(archive.FullPath, archive.Icon);
                    if (File.Exists(iconFile))
                    {
                        using (FileStream f = new FileStream(iconFile, FileMode.Open, FileAccess.Read))
                            item.pictureBox1.Image = Image.FromStream(f);
                        item.btnClear.Enabled = true;
                    }
                }
                item.comboBox1.SelectedIndex = 0;
                int index = 1;
                foreach (var group in groups)
                {
                    item.comboBox1.Items.Add(group.Name);
                    if (group.UUID == archive.GroupID) item.comboBox1.SelectedIndex = index;
                    index++;
                }
                DialogResult dialogResult = item.ShowDialog();
                if (dialogResult == DialogResult.OK)
                {
                    archive.Name = item.textBox1.Text;
                    archive.Application = item.textBox2.Text;
                    archive.ArchivePath = item.textBox3.Text;
                    archive.SteamID = item.textBox4.Text;
                    archive.SortNumber = int.Parse(item.textBox5.Text);
                    if (item.comboBox1.SelectedIndex > 0)
                        archive.GroupID = groups[item.comboBox1.SelectedIndex - 1].UUID;
                    else
                        archive.GroupID = string.Empty;
                    if (item.pictureBox1.Image != null)
                    {
                        archive.Icon = "Icon.png";
                        string iconFile = Path.Combine(archive.FullPath, archive.Icon);
                        if (File.Exists(iconFile)) File.Delete(iconFile);
                        using (FileStream f = new FileStream(iconFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            item.pictureBox1.Image.Save(f, ImageFormat.Png);
                        }
                    }
                    else
                    {
                        string iconFile = Path.Combine(archive.FullPath, "Icon.png");
                        if (File.Exists(iconFile)) File.Delete(iconFile);
                        archive.Icon = String.Empty;
                    }
                }
                return dialogResult;
            }
        }
        private void buttonSelectApplication_Click(object sender, EventArgs e)
        {
            openFileDialog1.Title = "请选择应用程序：";
            openFileDialog1.Filter = "应用程序（*.exe）|*.exe";
            openFileDialog1.Multiselect = false;
            openFileDialog1.FileName = this.textBox2.Text;
            openFileDialog1.InitialDirectory = Path.GetDirectoryName(this.textBox2.Text);
            if (openFileDialog1.ShowDialog() != DialogResult.OK) return;
            this.textBox2.Text = openFileDialog1.FileName;
        }

        private void buttonSelectArchivePath_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.ShowNewFolderButton = false;
            folderBrowserDialog1.Description = "请选择存档所在目录：";
            folderBrowserDialog1.SelectedPath = this.textBox3.Text;
            if (folderBrowserDialog1.ShowDialog() != DialogResult.OK) return;
            this.textBox3.Text = folderBrowserDialog1.SelectedPath;
        }
        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                if (textBox1.Text.IsNullOrEmpty())
                {
                    MessageBox.Show(this, "配置名称不能为空！", "保存失败", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    textBox1.Focus();
                    return;
                }
                if (textBox3.Text.IsNullOrEmpty() || !Directory.Exists(textBox3.Text.ExpandEnvironmentVariables()))
                {
                    MessageBox.Show(this, "存档位置不能为空或在一个不存在的位置！", "保存失败", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    textBox3.Focus();
                    return;
                }
                int sortNumber = int.Parse(textBox5.Text);
                if (sortNumber < 0 || sortNumber >= 100)
                {
                    MessageBox.Show(this, "排序号应当介于 0-99 之间！", "保存失败", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    textBox5.Focus();
                    return;
                }
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception e1)
            {
                e1.Error();
                MessageBox.Show(this, e1.Message, "保存失败", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.Title = "请选择图标文件：";
            openFileDialog1.Filter = "图标（*.ico;*.png;*.jpg）|*.ico;*.png;*.jpg";
            openFileDialog1.Multiselect = false;
            openFileDialog1.FileName = this.textBox2.Text;
            openFileDialog1.InitialDirectory = Path.GetDirectoryName(this.textBox2.Text);
            if (openFileDialog1.ShowDialog() != DialogResult.OK) return;
            pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
            btnClear.Enabled = true;
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            pictureBox1.Image = null;
            btnClear.Enabled = false;
        }
    }
}
